package com.zaozhuang.robot.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FaceDetectorManager {
    private Context mContext;
    private ExecutorService cameraExecutor;
    private long lastProcessTime = 0;
    // 状态变量
    private long lastAnnouncementTime = 0;    // 上次播报时间
    private long lastDisappearanceTime = 0;   // 首次检测到消失的时间
    private boolean isTrackingDisappearance = false;  // 是否正在跟踪消失
    boolean alreadyDisappeared = true;//定义的人脸消失： 人离开镜头3s才算消失
    private final long MIN_INTERVAL_MS = 500; // 例如：500ms 处理一次
    /**
     * 30s内最多播报一次，且人脸从显示到消失超过3s才播报
     */
    private static final long COOLDOWN_MS = 12000;        // 冷却时间30秒，30s内最多播报一次
    private static final long DISAPPEAR_THRESHOLD_MS = 900; // 消失判定3秒，
    private boolean isRobot = true;//false则是自己的手机调试， robot和手机预览还有采集帧方向去完全是乱的，得手动调整，坑逼
    private final Handler handler = new Handler(Looper.getMainLooper());
    // 回调接口
    public interface OnFaceDetectedListener {
        void onFaceDetected(int faceCount);
    }

    private OnFaceDetectedListener faceDetectedListener;

    public FaceDetectorManager(Context context, OnFaceDetectedListener listener) {
        this.mContext = context;
        this.faceDetectedListener = listener;
        cameraExecutor = Executors.newSingleThreadExecutor();
    }

    public void startCamera() {
        Log.e("potter","aaaa");
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(mContext);
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();

                // 配置图像分析
                ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                        .build();
                imageAnalysis.setAnalyzer(cameraExecutor, new ImageAnalysis.Analyzer() {
                    @Override
                    public void analyze(@NonNull ImageProxy imageProxy) {
                        Log.e("potter","bbbb");
                        long currentTime = System.currentTimeMillis();
                        if (currentTime - lastProcessTime >= MIN_INTERVAL_MS) {
                            Log.e("potter", "111111");
                            lastProcessTime = currentTime;
                            processImage(imageProxy);
                        } else {
                            imageProxy.close(); // 直接丢弃未处理的帧
                        }
                    }
                });

                // 绑定生命周期
                cameraProvider.unbindAll();
                //LENS_FACING_BACK/LENS_FACING_FRONT/LENS_FACING_EXTERNAL
                //实测机器人的外接摄像头竟然是LENS_FACING_BACK，而不是LENS_FACING_EXTERNAL
                int lensFacing = isRobot ? CameraSelector.LENS_FACING_BACK : CameraSelector.LENS_FACING_FRONT;
                CameraSelector cameraSelector = new CameraSelector.Builder()
                        .requireLensFacing(lensFacing)
                        .build();

                cameraProvider.bindToLifecycle(
                        (LifecycleOwner) mContext,
                        cameraSelector,//前后摄
                        imageAnalysis
                );

            } catch (ExecutionException | InterruptedException e) {
                Log.e("CameraX", "Error starting camera", e);
            }
        }, ContextCompat.getMainExecutor(mContext));
    }

    public Bitmap convertToRGB565(Bitmap srcBitmap) {
        // 确保宽度为偶数（FaceDetector 强制要求）
        int width = srcBitmap.getWidth();
        if (width % 2 != 0) {
            width--; // 或 width = srcBitmap.getWidth() - 1;
        }

        // 创建目标 Bitmap
        Bitmap rgb565Bitmap = Bitmap.createBitmap(
                width,
                srcBitmap.getHeight(),
                Bitmap.Config.RGB_565
        );

        // 通过 Canvas 复制像素
        Canvas canvas = new Canvas(rgb565Bitmap);
        Rect srcRect = new Rect(0, 0, width, srcBitmap.getHeight());
        Rect dstRect = new Rect(0, 0, width, srcBitmap.getHeight());
        canvas.drawBitmap(srcBitmap, srcRect, dstRect, null);

        // 回收原图（可选）
        srcBitmap.recycle();

        return rgb565Bitmap;
    }

    private void processImage(ImageProxy imageProxy) {
        // 注意：imageProxy.toBitmap生成的Bitmap格式是ARGB_8888的，FaceDetector 仅支持 Bitmap.Config.RGB_565 格式。得转下。
        Bitmap bitmap = convertToRGB565(imageProxyToBitmap(imageProxy));
        Log.e("potter Bitmap Config", bitmap.getConfig().toString());
        if (bitmap == null) {
            imageProxy.close();
            return;
        }

        // 检测人脸
        FaceDetector faceDetector = new FaceDetector(bitmap.getWidth(), bitmap.getHeight(), 1);
        FaceDetector.Face[] faces = new FaceDetector.Face[1];
        int detectedCount = faceDetector.findFaces(bitmap, faces);
        Log.e("potteraaaa detectedCount", "" + detectedCount);
        // 状态更新逻辑
        long currentTime = System.currentTimeMillis();
        if (detectedCount > 0) {
            // 人脸出现时，重置消失跟踪
            isTrackingDisappearance = false;
            lastDisappearanceTime = 0;
            if (alreadyDisappeared) {
                //人脸识别后的迎宾的逻辑写在这
                lastAnnouncementTime = currentTime;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("potter aaa","onFaceDetected");
                        faceDetectedListener.onFaceDetected(detectedCount);
                    }
                });
                alreadyDisappeared = false;
            } else {
            }
        } else {
            // 首次检测到消失，记录时间戳
            if (!isTrackingDisappearance) {
                lastDisappearanceTime = currentTime;
                isTrackingDisappearance = true;
            }

            // 检查是否满足消失条件：持续消失超过3秒
            if (currentTime - lastDisappearanceTime >= DISAPPEAR_THRESHOLD_MS) {
                // 检查冷却时间：距离上次播报超过30秒
                if (currentTime - lastAnnouncementTime >= COOLDOWN_MS) {
//                    triggerAnnouncement(); //
                    alreadyDisappeared = true;
                }
                // 重置消失跟踪（避免重复触发）
                isTrackingDisappearance = false;
            }
        }
        imageProxy.close();
//        imageProxy.close();
    }

    private void triggerAnnouncement() {
        // 示例：使用Toast播报
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.e("potter aaa","triggerAnnouncement");
                Toast.makeText(mContext, "人脸已持续消失3秒！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 将 ImageProxy（YUV）转换为 Bitmap（RGB）
    private Bitmap imageProxyToBitmap(ImageProxy imageProxy) {
        if (isRobot) {
            return imageProxy.toBitmap();
        }
        //实测手机上前摄toBitmap的图片是横着的，得旋转下
        int rotationDegrees = imageProxy.getImageInfo().getRotationDegrees();
        Bitmap bitmap = imageProxy.toBitmap();
        Matrix matrix = new Matrix();
        matrix.postRotate(rotationDegrees);
        // 创建一个新的Bitmap，其内容是旋转后的图像
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        // 如果不再需要原始bitmap，可以回收它
        bitmap.recycle();
        return rotatedBitmap;
    }


}
